import { defineStore } from 'pinia'

type Language = 'zh' | 'en'

interface UserState {
  username: string
  avatar: string
  lastVisitPosition: {
    x: number
    y: number
    z: number
  }
  visitedArticles: string[]
  favoriteArticles: string[]
  settings: {
    musicVolume: number
    sfxVolume: number
    movementSpeed: number
    language: Language
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    username: '',
    avatar: '',
    lastVisitPosition: {
      x: 0,
      y: 0,
      z: 0
    },
    visitedArticles: [] as string[],
    favoriteArticles: [] as string[],
    settings: {
      musicVolume: 0.5,
      sfxVolume: 0.5,
      movementSpeed: 1.0,
      language: 'zh' as Language
    }
  }),

  actions: {
    setUsername(username: string) {
      this.username = username
    },

    setAvatar(avatar: string) {
      this.avatar = avatar
    },

    setLastVisitPosition(x: number, y: number, z: number) {
      this.lastVisitPosition = { x, y, z }
    },

    addVisitedArticle(articleId: string) {
      if (!this.visitedArticles.includes(articleId)) {
        this.visitedArticles.push(articleId)
      }
    },

    toggleFavoriteArticle(articleId: string) {
      const index = this.favoriteArticles.indexOf(articleId)
      if (index === -1) {
        this.favoriteArticles.push(articleId)
      } else {
        this.favoriteArticles.splice(index, 1)
      }
    },

    updateSettings(settings: Partial<UserState['settings']>) {
      this.settings = { ...this.settings, ...settings }
    }
  },

  persist: true
})
